package com.jgzx.security.advice;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.jgzx.utils.PortalEncryptUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;

import java.io.*;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author libo
 * @date 2021/7/30 21:05
 */
@Slf4j
public class PortalDecryptHttpInputMessage implements HttpInputMessage {

    private HttpHeaders headers;

    private InputStream body;

    public PortalDecryptHttpInputMessage(HttpInputMessage inputMessage) throws Exception {
        this.headers = inputMessage.getHeaders();
        String content = new BufferedReader(new InputStreamReader(inputMessage.getBody())).lines().collect(Collectors.joining(System.lineSeparator()));
        Map map = JSON.parseObject(content, Map.class);
        String encryptContent = (String)map.get("param");
        if (StrUtil.isNotEmpty(encryptContent)) {
            encryptContent = PortalEncryptUtil.aesDecrypt(encryptContent);
        }
        log.info("加密数据：{}，解密后：{}", content, encryptContent);
        this.body = new ByteArrayInputStream(encryptContent.getBytes());
    }

    @Override
    public InputStream getBody() throws IOException {
        return body;
    }

    @Override
    public HttpHeaders getHeaders() {
        return headers;
    }
}
